package com.ys.erp.common.util;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ys.erp.common.enums.RedisKey;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author lwj
 * @date 2023/5/10
 */
@Component
@RequiredArgsConstructor
public class EmpByRequestUtil {

    private final RedisTemplate<String, String> redisTemplate;


    public String getEmpDtoByRequest(HttpServletRequest request) {
        //未登录用户
        if (StringUtils.isBlank(request.getHeader("token"))) {
            return null;
        }
        String token = request.getHeader("token");
        String empStr = redisTemplate.opsForValue().get(RedisKey.Enums.EMP_LOGIN_FLAG.getKey() + token);
        if (ObjectUtil.isEmpty(empStr)) {
            //token过期
            return null;
        }
        return empStr;
    }

    public List<String> getEmpRightsByRequest(HttpServletRequest request) {
        //未登录用户
        if (ObjectUtil.isEmpty(request.getHeader("token"))) {
            return null;
        }
        String token = request.getHeader("token");
        String empStr = redisTemplate.opsForValue().get(RedisKey.Enums.EMP_LOGIN_FLAG.getKey() + token);
        if (ObjectUtil.isEmpty(empStr)) {
            //token过期
            return null;
        }
        JSONObject obj = JSONObject.parseObject(empStr);
        if (Objects.isNull(obj)) {
            return new ArrayList<>();
        }
        JSONArray array = obj.getJSONArray("rightFlags");
        return array.toJavaList(String.class);
    }

}
